package controller;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.xmlbeans.XmlException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import domain.ContractModel;
import domain.Return;
import service.ContractModelServiceImp;
import service.ContractTypeServiceImp;
import utils.TextUtils;

/**
 * User: xinxin
 * Date: 2016-10-27
 * Time: 22:30
 * FIXME
 */
@Controller
@RequestMapping("/specific_lawyer")
public class SpecificLawyerController {
    private static final Logger LOG = LoggerFactory.getLogger(SpecificLawyerController.class);
    @Autowired
    ContractModelServiceImp mContractModelServiceImp;
    @Autowired
    ContractTypeServiceImp mContractTypeServiceImp;


    @RequestMapping("/json_contract_all/{pageIndex}")
    @ResponseBody
    public Return jsonContractShowAll(@PathVariable("pageIndex") int pageIndex) {
        List<ContractModel> contractModels = mContractModelServiceImp.selectModelAll(pageIndex);
        if (contractModels != null&&contractModels.size()>0) {
            return Return.commonReturn().setPageNum(pageIndex).setData(contractModels);
        } else {
            return Return.faliReturn().setMesg("没有内容了");
        }
    }

    @RequestMapping("/json_contract/{contractId}")
    @ResponseBody
    public Return jsonContractShowOne(@PathVariable("contractId") int contractId) {
        ContractModel contractModel = mContractModelServiceImp.selectModelById(contractId);
        if (contractModel != null) {
            String fileLocation = contractModel.getLocation();
            if (fileLocation != null) {
                System.out.println(fileLocation);
                //转义特殊字符
                fileLocation = TextUtils.parseRight(fileLocation);
            } else {
                return Return.faliReturn().setMesg("暂无内容");
            }
            //这里要获取word并转化为文本返回
            //doc
            if (fileLocation.charAt(fileLocation.length() - 1) == 'x') {
                //docx
                OPCPackage opcPackage = null;
                try {
                    opcPackage = POIXMLDocument.openPackage(fileLocation);
                    POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
                    String text2007 = extractor.getText();
                    //System.out.println(text2007);
                    return Return.commonReturn().setData(text2007);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (XmlException e) {
                    e.printStackTrace();
                } catch (OpenXML4JException e) {
                    e.printStackTrace();
                }
            } else {
                try {

                    WordExtractor wordExtractor = new WordExtractor(new FileInputStream(fileLocation));
                    String text2003 = wordExtractor.getText();
                    //System.out.println(text2003);
                    return Return.commonReturn().setData(text2003);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Return.faliReturn().setMesg("暂无内容");
    }


    @RequestMapping("/download_contract/{contract_id}")
    @ResponseBody
    public ResponseEntity<byte[]> downloadContract(@PathVariable("contract_id") int contractId) {
        final ContractModel contractModel = mContractModelServiceImp.selectModelById(contractId);
        if (contractModel != null) {
            String fileName = FilenameUtils.getName(contractModel.getLocation());
            String dfileName = null;
            try {
                dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", dfileName);
            try {
                return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(TextUtils.parseRight(contractModel.getLocation()))), headers, HttpStatus.CREATED);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
//    @RequestMapping("/json_contract_type_all/{pageIndex}")
//    @ResponseBody
//    public List<ContractType> jsonContractTypeAll(@PathVariable("pageIndex") int pageIndex) {
//        List<ContractType> contractTypes = mContractTypeServiceIImp.selectModelTypeAll(pageIndex);
//        for (ContractType contractType : contractTypes) {
//            System.out.println(contractType);
//        }
//        return contractTypes;
//    }
}
